package com.qf.filter;

import com.qf.util.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpCookie;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器
 * @author 千锋健哥
 */
@Component
public class AuthFilter implements Ordered, GlobalFilter {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1. 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        //2. 获取响应对象
        ServerHttpResponse response = exchange.getResponse();
        //3. 判断用户访问的url路径, 如果是注册路径, 是认证路径放行
        String uri = request.getURI().getPath();
        if (uri.contains("/auth/login")
                || uri.contains("/auth/register")) {
            //放行
            return chain.filter(exchange);
        }

        //4. 其他路径需要获取cookie中的jwt
        HttpCookie httpCookie = request.getCookies().getFirst("token");
        if (httpCookie == null) {
            //设置返回状态码401, 权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
        String jwt = httpCookie.getValue();
        if (StringUtils.isEmpty(jwt)) {
            //设置返回状态码401, 权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }

        //5. 解析jwt
        try {
            Claims claims = JwtUtil.parseJWT(jwt);
            //6. 解析成功将解析后的内容放入当前请求头中放行
            request.mutate().header("authorization", claims.getSubject());
            //放行
            return chain.filter(exchange);
        } catch (Exception e) {
            //7. 解析失败, 抛出401权限不足异常
            //设置返回状态码401, 权限不足
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //返回响应
            return response.setComplete();
        }
    }

    @Override
    public int getOrder() {
        return 0;
    }

}
